<template>
    <el-form :inline="true" :model="TJ" class="demo-form-inline">
        <el-form-item label="姓名">
            <el-input v-model="TJ.ApplicantName" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="审批状态">
            <el-select v-model="TJ.State" placeholder="请选择审批状态" clearable>
                <el-option label="未审批" :value="1" />
                <el-option label="已通过" :value="2" />
                <el-option label="已驳回" :value="3" />
            </el-select>
        </el-form-item>
        <el-form-item label="日期">
            <el-date-picker v-model="TJ.StartTime" type="date" placeholder="请选择开始日期" clearable />---
            <el-date-picker v-model="TJ.EndTime" type="date" placeholder="请选择结束日期" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="ShowRequest">查询</el-button>
        </el-form-item>
    </el-form>

    <el-button type="primary" v-if="store.Account.DepartmentHead!=store.Account.Name" plain @click="dialogFormVisible = true">
        申请
    </el-button>
    <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="编号" width="60" />
        <el-table-column prop="ApplicantName" label="姓名" width="80" />
        <el-table-column prop="DepartmentName" label="部门" width="100">
            <template v-slot="scope">
                <span v-if="scope.row.DepartmentName == 1">IT部门</span>
                <span v-if="scope.row.DepartmentName == 2">人力资源部</span>
                <span v-if="scope.row.DepartmentName == 3">财务部</span>
                <span v-if="scope.row.DepartmentName == 4">销售部</span>
            </template>
        </el-table-column>
        <el-table-column prop="RequestType" label="请假类别" width="100" />
        <el-table-column label="请假时间" width="200">
            <template v-slot="scope">
                <span>{{ moment(scope.row.StartTime).format("YYYY-MM-DD") }}至
                    {{ moment(scope.row.EndTime).format("YYYY-MM-DD") }}
                </span>
            </template>
        </el-table-column>
        <el-table-column prop="TotalTime" label="总工时" width="80" />
        <el-table-column prop="ReportTime" label="报道时间" width="110">
            <template v-slot="scope">
                <span>{{ moment(scope.row.ReportTime).format("YYYY-MM-DD") }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="RequestContent" label="请假事由" width="100" />
        <el-table-column prop="DepartmentHead" label="部门领导" width="100" />
        <el-table-column prop="State" label="审批状态" width="100">
            <template v-slot="scope">
                <span v-if="scope.row.State == 1">未审批</span>
                <span  v-if="scope.row.State == 2">已通过</span>
                <span  v-if="scope.row.State == 3">已驳回</span>
            </template>
        </el-table-column>
        <el-table-column prop="CreateDate" label="创建日期" width="180">
            <template v-slot="scope">
                <span>{{ moment(scope.row.CreateDate).format("YYYY-MM-DD HH:mm:ss") }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="230">
            <template v-slot="scope">
                <el-button @click="DelRequest(scope.row.Id)" v-if="scope.row.State==1&&scope.row.ApplicantName==store.Account.Name" type="primary" plain>删除</el-button>
                <el-button @click="UpdRequest(scope.row)" v-if="scope.row.State==1&&scope.row.ApplicantName==store.Account.Name" type="success" plain>编辑</el-button>
                <el-button @click="request(scope.row)" v-if="scope.row.DepartmentHead==store.Account.Name&&scope.row.State!=2&&scope.row.State!=3" type="success" plain>审批</el-button>
            </template>
        </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
        <el-pagination v-model:current-page="Total.PageIndex" v-model:page-size="Total.PageSize"
            :page-sizes="[15, 30, 45, 60]" :size="size" :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total="Total.TotalCount" />
    </div>

    <el-dialog v-model="dialogFormVisible" title="申请" width="800">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="姓名" prop="ApplicantName">
                <el-input v-model="ruleForm.ApplicantName" disabled />
            </el-form-item>
            <el-form-item label="部门">
                <el-select v-model="ruleForm.DepartmentName" placeholder="请选择部门" disabled clearable>
                    <el-option label="IT部门" :value="1" />
                    <el-option label="人力资源部" :value="2" />
                    <el-option label="财务部" :value="3" />
                    <el-option label="销售部" :value="4" />
                </el-select>
            </el-form-item>
            <el-form-item label="请假类别" prop="RequestType">
                <el-radio-group v-model="ruleForm.RequestType">
                    <el-radio value="事假">事假</el-radio>
                    <el-radio value="病假">病假</el-radio>
                    <el-radio value="婚假">婚假</el-radio>
                    <el-radio value="丧假">丧假</el-radio>
                    <el-radio value="产假">产假</el-radio>
                    <el-radio value="补休">补休</el-radio>
                    <el-radio value="工伤">工伤</el-radio>
                    <el-radio value="其他">其他</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="请假时间">
                <el-date-picker v-model="ruleForm.StartTime" type="datetime" placeholder="请选择开始时间" />-
                <el-date-picker v-model="ruleForm.EndTime" type="datetime" placeholder="请选择结束时间" />

                <el-col :span="15">共计{{ durationText }}</el-col>
                <br /><br />

                <el-form-item label="报道时间">
                    <el-date-picker v-model="ruleForm.ReportTime" type="datetime" placeholder="请选择报道时间" />
                </el-form-item>
            </el-form-item>
            <el-form-item label="请假事由" prop="textarea">
                <el-input v-model="ruleForm.RequestContent" type="textarea" />
            </el-form-item>
            <el-form-item label="部门领导" prop="DepartmentHead">
                <el-input v-model="ruleForm.DepartmentHead" disabled />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确定
                </el-button>
                <el-button @click="dialogFormVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>


    <el-dialog v-model="UpddialogFormVisible" title="编辑" width="800">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="姓名" prop="ApplicantName">
                <el-input v-model="ruleForm.ApplicantName" disabled />
            </el-form-item>
            <el-form-item label="部门">
                <el-select v-model="ruleForm.DepartmentName" placeholder="请选择部门" disabled clearable>
                    <el-option label="IT部门" :value="1" />
                    <el-option label="人力资源部" :value="2" />
                    <el-option label="财务部" :value="3" />
                    <el-option label="销售部" :value="4" />
                </el-select>
            </el-form-item>
            <el-form-item label="请假类别" prop="RequestType">
                <el-radio-group v-model="ruleForm.RequestType">
                    <el-radio value="事假">事假</el-radio>
                    <el-radio value="病假">病假</el-radio>
                    <el-radio value="婚假">婚假</el-radio>
                    <el-radio value="丧假">丧假</el-radio>
                    <el-radio value="产假">产假</el-radio>
                    <el-radio value="补休">补休</el-radio>
                    <el-radio value="工伤">工伤</el-radio>
                    <el-radio value="其他">其他</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="请假时间">
                <el-date-picker v-model="ruleForm.StartTime" type="datetime" placeholder="请选择开始时间" />-
                <el-date-picker v-model="ruleForm.EndTime" type="datetime" placeholder="请选择结束时间" />

                <el-col :span="15">共计{{ durationText }}</el-col>
                <br /><br />

                <el-form-item label="报道时间">
                    <el-date-picker v-model="ruleForm.ReportTime" type="datetime" placeholder="请选择报道时间" />
                </el-form-item>
            </el-form-item>
            <el-form-item label="请假事由" prop="textarea">
                <el-input v-model="ruleForm.RequestContent" type="textarea" />
            </el-form-item>
            <el-form-item label="部门领导" prop="DepartmentHead">
                <el-input v-model="ruleForm.DepartmentHead" disabled />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="UpdsubmitForm(ruleFormRef)">
                    确定
                </el-button>
                <el-button @click="UpddialogFormVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog v-model="AppdialogFormVisible" title="审批" width="800">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="姓名" prop="ApplicantName">
                <el-input v-model="ruleForm.ApplicantName" disabled />
            </el-form-item>
            <el-form-item label="部门">
                <el-select v-model="ruleForm.DepartmentName" placeholder="请选择部门" disabled clearable>
                    <el-option label="IT部门" :value="1" />
                    <el-option label="人力资源部" :value="2" />
                    <el-option label="财务部" :value="3" />
                    <el-option label="销售部" :value="4" />
                </el-select>
            </el-form-item>
            <el-form-item label="请假类别" prop="RequestType">
                <el-input v-model="ruleForm.RequestType" disabled />
            </el-form-item>
            <el-form-item label="请假时间">
                <el-date-picker disabled v-model="ruleForm.StartTime" type="datetime" placeholder="请选择开始时间" />-
                <el-date-picker disabled v-model="ruleForm.EndTime" type="datetime" placeholder="请选择结束时间" />

                <el-col :span="15">共计{{ durationText }}</el-col>
                <br /><br />

                <el-form-item label="报道时间">
                    <el-date-picker disabled v-model="ruleForm.ReportTime" type="datetime" placeholder="请选择报道时间" />
                </el-form-item>
            </el-form-item>
            <el-form-item label="请假事由" prop="textarea">
                <el-input disabled v-model="ruleForm.RequestContent" type="textarea" />
            </el-form-item>
            <el-form-item label="审核" prop="RequestType">
                <el-radio-group v-model="ruleForm.State">
                    <el-radio :value="2">通过</el-radio>
                    <el-radio :value="3">不通过</el-radio>
                    <el-input v-if="ruleForm.State=='3'" v-model="ruleForm.Reason" placeholder="请说明原因" />
                </el-radio-group>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="AppsubmitForm(ruleFormRef)">
                    确定
                </el-button>
                <el-button @click="AppdialogFormVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script lang="ts" setup>
import axios from 'axios';
import moment, { duration } from 'moment';
import { onMounted, reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter';
import http from '@/http/axiosHelper';
const store = useCounterStore()

const tableData = ref([])
const Total = ref({
    TotalCount: 1,
    TotalPage: 1,
    PageIndex: 1,
    PageSize: 15
})
const TJ = ref({
    StartTime: "",
    EndTime: "",
    State: "",
    ApplicantName: "",
    LoginName: store.Account.Name,
})
onMounted(() => {
    ShowRequest()
})
const ShowRequest = () => {
    http.get("/api/Request/GetRequest", {
        params: {
            PageIndex: Total.value.PageIndex,
            PageSize: Total.value.PageSize,
            StartTime: TJ.value.StartTime,
            EndTime: TJ.value.EndTime,
            State: TJ.value.State,
            ApplicantName: TJ.value.ApplicantName,
            LoginName: TJ.value.LoginName
        }
    }).then(res => {
        tableData.value = res.data.PageDatas
        Total.value.TotalCount = res.data.TotalCount
        Total.value.TotalPage = res.data.TotalPage
    })
}
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
watch(Total, () => {
    ShowRequest()
}, { deep: true })
//新增
const dialogFormVisible = ref(false)
const ruleForm = reactive({
    "ApplicantName": store.Account.Name,
    "DepartmentName": store.Account.Department,
    "RequestType": "",
    "StartTime": "",
    "EndTime": "",
    "ReportTime": "",
    "RequestContent": "",
    "DepartmentHead": store.Account.DepartmentHead,
    "Reason": "",
    "State": ""
})
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    Name: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },
    ],
  textarea: [
       { min: 0, max: 140, message: '不能超过140字!', trigger: 'blur' },
  ],
})
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            http.post("/api/Request/CreateRequst", ruleForm).then(res => {
                if (res.data.Code == 200) {
                    ElMessage.success(res.data.Message)
                    dialogFormVisible.value = false
                    ShowRequest()
                }
                else {
                    ElMessage.warning(res.data.Message)
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
const durationText = ref('0小时')
watch(() => [ruleForm.StartTime, ruleForm.EndTime],
    ([start, end]) => {
        if (start && end) {
            calculateDuration(new Date(start), new Date(end));
        }
        else {
            durationText.value = '0小时'
        }
    }, { deep: true })
function calculateDuration(start: Date, end: Date) {
    if (end < start) {
        durationText.value = '0小时';
        return;
    }
    const diffInMs = end.getTime() - start.getTime();
    const diffInHours = Math.floor(diffInMs / (1000 * 60 * 60))
    if (diffInHours >= 8) {
        const days = Math.floor(diffInHours / 8);
        const remainingHours = diffInHours % 8;
        if (remainingHours > 0) {
            durationText.value = `${days}天${remainingHours}小时`;
        } else {
            durationText.value = `${days}天`;
        }
    } else {
        durationText.value = `${diffInHours}小时`;
    }
};

//修改
const UpddialogFormVisible = ref(false)
const UpdRequest = (row: any) => {
    UpddialogFormVisible.value = true
    const formattedRow = {
        ...row,
        StartTime: row.StartTime ? new Date(row.StartTime) : null,
        EndTime: row.EndTime ? new Date(row.EndTime) : null
    };
    Object.assign(ruleForm, formattedRow);
}
const UpdsubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            http.post("/api/Request/UpdateRequest", ruleForm).then(res => {
                if (res.data.Code == 200) {
                    ElMessage.success(res.data.Message)
                    ShowRequest()
                    UpddialogFormVisible.value = false;
                }
                else {
                    ElMessage.warning(res.data.Message)
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
//删除
const DelRequest = (id: any) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        http.get("/api/Request/DelRequest", { params: { Id: id } }).then(res => {
            if (res.data.Code == 200) {
                ElMessage.success(res.data.Message)
                ShowRequest()
            }
            else {
                ElMessage.warning(res.data.Message)
            }
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消删除',
        })
    })
}
//审批
const AppdialogFormVisible = ref(false)
const request = (row: any) => {
    AppdialogFormVisible.value = true
    ruleForm.ApplicantName = row.ApplicantName
    ruleForm.DepartmentName = row.DepartmentName
    const formattedRow = {
        ...row,
        StartTime: row.StartTime ? new Date(row.StartTime) : null,
        EndTime: row.EndTime ? new Date(row.EndTime) : null
    };
    Object.assign(ruleForm, formattedRow);
}
const AppsubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            http.post("/api/Request/UpdStateRequest", ruleForm).then(res => {
                if (res.data.Code == 200) {
                    ElMessage.success(res.data.Message)
                    ShowRequest()
                    AppdialogFormVisible.value = false;
                }
                else {
                    ElMessage.warning(res.data.Message)
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>
<style>
.el-popper.is-customized {
    /* Set padding to ensure the height is 32px */
    padding: 6px 12px;
    background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
    background: linear-gradient(45deg, #b2e68d, #bce689);
    right: 0;
}

.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}
</style>